<script setup lang="tsx">
import { useVbenForm, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { Page } from '@vben/common-ui';

import { Button, message, Space } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import {
  deleteDict,
  dictAdd,
  getDict,
  updateDict,
} from '#/api/core/popularize';

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,

  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: '名称',
    },
  ],
  // 是否可展开
  showCollapseButton: false,
  submitOnChange: true,
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-4',
};

const enums = {
  status: [
    {
      label: '启用',
      value: true,
      color: 'blue',
    },
    {
      label: '禁用',
      value: false,
    },
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { title: '序号', field: 'sort', width: 50 },
    { field: 'id', title: 'ID' },
    { field: 'name', title: '名称' },
    { field: 'code', title: '编码' },
    { field: 'value', title: '值' },
    { field: 'description', title: '描述' },
    {
      cellRender: { name: 'CellTag', options: enums.status },
      field: 'enabled',

      title: '状态',
    },
    {
      align: 'right',
      cellRender: {
        attrs: {
          nameField: 'title',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          'edit', // 默认的编辑按钮
          // 'delete', // 默认的删除按钮
        ],
      },
      field: 'operation',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      title: '操作',
      width: 100,
    },
  ],
  editConfig: {
    mode: 'row',
    trigger: 'click',
  },
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 10,
  },
  proxyConfig: {
    response: {
      result: 'list',
      total: 'total',
      list: 'list',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getDict({
          currentPage: page.currentPage,
          pageSize: page.pageSize,
          filter: {
            ...formValues,
          },
        });
        return res.data;
      },
    },
  },
  showOverflow: false,
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
function onRefresh() {
  gridApi.query();
}

function onDelete(row: any) {
  deleteDict({ id: row.id })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {});
}
function onActionClick({ code, row }: { code: string; row: any }) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    default: {
      break;
    }
  }
}
const [BaseForm, baseFormApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-[80%]',
    },
  },
  showDefaultActions: false,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      rules: 'required',
      label: '名称',
    },
    {
      component: 'Input',
      fieldName: 'code',
      rules: 'required',
      label: '编码',
    },
    {
      component: 'Input',
      fieldName: 'value',
      rules: 'required',
      label: '值',
    },
    {
      component: 'Textarea',
      componentProps: {
        autoSize: { minRows: 2, maxRows: 5 },
      },
      fieldName: 'description',
      label: '描述',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: enums.status,
      },
      defaultValue: true,
      fieldName: 'enabled',
      label: '状态',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 1,
      },
      fieldName: 'sort',
      label: '排序',
    },
  ],

  wrapperClass: 'grid-cols-1',
});
const formData = ref({});

const [Modal1, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    modalApi.setState({
      confirmLoading: true,
    });
    baseFormApi
      .validateAndSubmitForm()
      .then((val) => {
        if (val) {
          const param: any = {
            ...val,
          };

          if (formData.value.id) {
            updateDict({
              ...param,
              id: formData.value.id,
              dictTypeId: formData.value.id,
            }).then((res) => {
              if (res.success === true) {
                message.success('添加成功');
                modalApi.close();
                onRefresh();
              } else {
                message.error(res.msg);
              }
            });
          } else {
            dictAdd(param).then((res) => {
              if (res.success === true) {
                message.success('添加成功');
                modalApi.close();
                onRefresh();
              } else {
                message.error(res.msg);
              }
            });
          }
        }
      })
      .finally(() => {
        modalApi.setState({
          confirmLoading: false,
        });
      });
  },
});
function addGoods() {
  formData.value = {};
  modalApi.open();
}
function onEdit(row: any) {
  baseFormApi.setValues({
    ...row,
  });
  formData.value = { ...row };
  modalApi.open();
}
</script>
<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="addGoods"> 新增配置项 </Button>
        </Space>
      </template>
    </Grid>
    <Modal1 class="w-[40vw]" title="修改配置项">
      <BaseForm />
    </Modal1>
  </Page>
</template>

<style lang="scss" scoped>
.page {
  background: white;
  padding: 20px;
}
</style>
<style>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
